<template>
  <el-dialog :visible.sync="visible" :title="!dataForm.id ? $t('add') : $t('update')" :close-on-click-modal="false"
    :close-on-press-escape="false" top="80px">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmitHandle()"
      label-width="100px">
      <el-col :span="12">
        <el-form-item prop="title" label="标题">
          <el-input v-model="dataForm.title" placeholder=""></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <p class="pdl60">
          <span class="tip">*</span> 缩略图<span>(支持png、jpg，建议尺寸288*288px，最多1张)</span>
        </p>
      </el-col>
      <el-col :span="24">
        <el-form-item label="" prop="pic">
          <el-upload class="avatar-uploader" :action="url" :show-file-list="false"
            :on-success="(res, file) => successHandle1(res, file)" :before-upload="beforeUploadHandle">
            <img v-if="dataForm.pic" :src="dataForm.pic" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-col>

      <el-col :span="24">
        <el-form-item label="内容" prop="content">
          <editor-vue :content="dataForm.content" @EditorChange="getEditor" ref="infoIntroduceRef"></editor-vue>
        </el-form-item>
      </el-col>
    </el-form>
    <template slot="footer">
      <el-button @click="visible = false">{{ $t("cancel") }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{
        $t("confirm")
      }}</el-button>
    </template>
  </el-dialog>
</template>

<script>
import Cookies from "js-cookie";
import debounce from "lodash/debounce";
import editorVue from "@/components/editor";
export default {
  components: {
    editorVue,
  },
  data() {
    return {
      visible: false,
      url: `${window.SITE_CONFIG["apiURL"]
        }/oss/file/aliyunUpload?access_token=${Cookies.get("access_token")}`,
      dataForm: {
        title: "",
        id: "",
        content: "",
        type: 8,
        pic: "",
      },
    };
  },
  computed: {
    dataRule() {
      return {
        title: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        pic: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        content: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
      };
    },
  },
  methods: {
    getEditor(val) {
      this.dataForm.content = val;
    },
    init() {
      this.visible = true;
      this.$nextTick(() => {
        setTimeout(() => {
          this.$refs.infoIntroduceRef.init();
        }, 500);
        this.$refs["dataForm"].resetFields();
        if (this.dataForm.id) {
          this.getInfo();
        }
      });
    },
    // 获取信息
    getInfo() {
      this.$http
        .get(`/scenic/newsagriculturalproducts/${this.dataForm.id}`)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          }
          this.dataForm = {
            ...this.dataForm,
            ...res.data,
          };
        })
        .catch(() => { });
    },
    // 上传之前
    beforeUploadHandle(file) {
      if (
        file.type !== "image/jpg" &&
        file.type !== "image/jpeg" &&
        file.type !== "image/png" &&
        file.type !== "image/gif"
      ) {
        this.$message.error(
          this.$t("upload.tip", {
            format: "jpg、png、gif",
          })
        );
        return false;
      }
    },
    // 上传成功
    successHandle1(res, file) {
      if (res.code !== 0) {
        return this.$message.error(res.msg);
      }
      this.dataForm.pic = res.data.url;
    },
    // 表单提交
    dataFormSubmitHandle: debounce(
      function () {
        this.$refs["dataForm"].validate((valid) => {
          if (!valid) {
            return false;
          }
          this.$http[!this.dataForm.id ? "post" : "put"](
            "/scenic/newsagriculturalproducts",
            this.dataForm
          )
            .then(({ data: res }) => {
              if (res.code != 0) {
                return this.$message.error(res.msg);
              }
              this.$message({
                message: this.$t("prompt.success"),
                type: "success",
                duration: 500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                },
              });
            })
            .catch(() => { });
        });
      },
      1000,
      {
        leading: true,
        trailing: false,
      }
    ),
  },
};
</script>
<style lang="scss" scoped>
.pdl60 {
  padding-left: 47px;

  .tip {
    color: #F56C6C;
  }
}
</style>